﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using InstituteManager.Bussiness;
using InstituteManager.Data;
using System.Security.Cryptography;

namespace InstituteManager.adm
{
    public partial class Student : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // hide message            
            pnlMessage.Visible = false;
            if (!IsPostBack)
            {
                lbtDeleteT.Attributes.Add("onClick", "javascript:return confirm(\"Are you sure ?\")");
                lbtDeleteB.Attributes.Add("onClick", "javascript:return confirm(\"Are you sure ?\")");
                gridBind();
                GeneralDateControls(ddlDOBDay, ddlDOBMonth, ddlDOBYear);
            }
        }

        protected void GeneralDateControls(DropDownList ddlDay , DropDownList ddlMon, DropDownList ddlYear){
            for (int i = 1; i <= 31; i++)
                ddlDay.Items.Add(new ListItem(i+"", i+""));
            for (int i = 1; i <= 12; i++ )
                ddlMon.Items.Add(new ListItem(i + "", i + ""));
            for (int i = 1900; i <= DateTime.Now.Year; i++)
                ddlYear.Items.Add(new ListItem(i + "", i + ""));
        }

        protected void gridBind()
        {
            grvView.DataSource = StudentBL.getByAll();
            grvView.DataBind();
        }

        public string GetMD5(string chuoi)
        {
            string str_md5 = "";
            byte[] mang = System.Text.Encoding.UTF8.GetBytes(chuoi);

            MD5CryptoServiceProvider my_md5 = new MD5CryptoServiceProvider();
            mang = my_md5.ComputeHash(mang);

            foreach (byte b in mang)
            {
                str_md5 += b.ToString("X2").ToLower();
            }

            return str_md5;
        }


        protected void ResetControl()
        {
            txtId.Text = "";

            txtStudentName.Text = "";
            txtAddress.Text = "";
            txtStudentPhone.Text = "";
            txtEmail.Text = "";
            txtUsername.Text = "";

            ddlDOBYear.SelectedIndex = 0;
            ddlDOBMonth.SelectedIndex = 0;
            ddlDOBDay.SelectedIndex = 0;
        }

        protected void grvView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
                ((CheckBox)e.Row.FindControl("chkSelectAll")).Attributes.Add("onClick", "SelectAllClick(this)");
            if (e.Row.RowType == DataControlRowType.DataRow)
                ((CheckBox)e.Row.FindControl("chkSelect")).Attributes.Add("onClick", "SelectClick(this)");
        }

        protected void lbtAddnew_Click(object sender, EventArgs e)
        {
            pnlView.Visible = false;
            pnlUpdate.Visible = true;
            pnlPassword.Visible = true;

            txtUsername.ReadOnly = false;
            txtUsername.Style["background-color"] = "";
            ResetControl();
        }

        protected void lbtBack_Click(object sender, EventArgs e)
        {
            pnlView.Visible = true;
            pnlUpdate.Visible = false;
        }

        protected void lbtSave_Click(object sender, EventArgs e)
        {
            string strId = txtId.Text;
            
            Data.tbl_Student entt = new Data.tbl_Student();
            entt.StudentName = txtStudentName.Text;

            if (ddlDOBDay.SelectedIndex > 0 && ddlDOBMonth.SelectedIndex > 0 && ddlDOBYear.SelectedIndex > 0)
                entt.DOB = new DateTime(int.Parse(ddlDOBYear.SelectedValue), int.Parse(ddlDOBMonth.SelectedValue), int.Parse(ddlDOBDay.SelectedValue));

            entt.Address = txtAddress.Text;
            entt.StudentPhone = txtStudentPhone.Text;
            entt.Username = txtUsername.Text;
            entt.Email = txtEmail.Text;
            entt.Password = GetMD5(txtPassword.Text);
            // if strId = "" then add new else update
            if (strId.Trim() == "")
            {
                if (StudentBL.AddNew(entt))
                {
                    ShowMessage(1, "Data added successfully ! ");
                    gridBind();
                }
                else
                {
                    ShowMessage(0, "Data added fail : " + StudentBL.errorMsg);
                }
            }
            else
            {
                entt.StudentId = int.Parse(strId);
                if (StudentBL.Update(entt))
                {
                    ShowMessage(1, "Data updated successfully ! ");
                    gridBind();
                }
                else
                {
                    ShowMessage(0, "Data updated fail : " + StudentBL.errorMsg);
                }
            }

            pnlView.Visible = true;
            pnlUpdate.Visible = false;
            gridBind();
        }


        protected void ShowMessage(int MegType, string Message)
        {
            pnlMessage.Visible = true;
            ((Label)pnlMessage.FindControl("lblMessage")).Text = Message;
            switch (MegType)
            {
                case 1:
                    pnlMessage.CssClass = "sukses";
                    break;
                case 0:
                    pnlMessage.CssClass = "gagal";
                    break;
                default:
                    pnlMessage.CssClass = "informasi";
                    break;
            }
        }

        protected void grvView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvView.PageIndex = e.NewPageIndex;
            gridBind();
        }

        protected void grvView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string strId = e.CommandArgument.ToString();
            Data.tbl_Student obj = new tbl_Student();
            switch (e.CommandName)
            {
                case "cmdEdit":
                    txtId.Text = strId;
                    obj = StudentBL.getById(int.Parse(strId));
                    txtStudentName.Text = obj.StudentName;
                    if (obj.DOB != null)
                    {
                        ddlDOBDay.SelectedValue = obj.DOB.Value.Day.ToString();
                        ddlDOBMonth.SelectedValue = obj.DOB.Value.Month.ToString();
                        ddlDOBYear.SelectedValue = obj.DOB.Value.Year.ToString();
                    }
                    txtAddress.Text = obj.Address;
                    txtStudentPhone.Text = obj.StudentPhone;
                    txtUsername.Text = obj.Username;
                    txtEmail.Text = obj.Email;
                    pnlUpdate.Visible = true;
                    pnlView.Visible = false;
                    // hide controls password.
                    pnlPassword.Visible = false;
                    txtUsername.ReadOnly = true;
                    txtUsername.Style["background-color"] = "Silver";
                    break;
                case "cmdView":
                    obj = StudentBL.getById(int.Parse(strId));
                    lblStudentName.Text = obj.StudentName;
                    lblDOB.Text = obj.DOB.Value.ToString("d");
                    lblAddress.Text = obj.Address;
                    lblPhone.Text = obj.StudentPhone;                    
                    lblUsername.Text = obj.Username;
                    lblEmail.Text = obj.Email;

                    pnlView.Visible = false;
                    pnlDetail.Visible = true;
                    break;
                case "cmdDelete":
                    if (StudentBL.Delete(int.Parse(strId)))
                    {
                        ShowMessage(1, "Data deleted successfully ! ");
                        gridBind();
                    }
                    else
                    {
                        ShowMessage(0, "Data deleted fail : " + StudentBL.errorMsg);
                    }
                    break;
            }
        }

        protected void lbtRefresh_Click(object sender, EventArgs e)
        {
            gridBind();
        }

        protected void lbtDelete_Click(object sender, EventArgs e)
        {
            bool result = true;
            bool isChecked = false;
            foreach (GridViewRow row in grvView.Rows)
            {
                if (row.RowType == DataControlRowType.DataRow)
                {
                    if (((CheckBox)row.FindControl("chkSelect")).Checked == true)
                    {
                        isChecked = true;
                        if (!StudentBL.Delete(int.Parse(grvView.DataKeys[row.RowIndex].Value.ToString())))
                            result = false;
                    }
                }
            }

            if (isChecked == false)
                ShowMessage(-1, "You have not selected data to delete ! ");
            else if (result)
            {
                ShowMessage(1, "Data deleted successfully ! ");
                gridBind();
            }
            else
            {
                ShowMessage(0, "Data deleted fail : " + StudentBL.errorMsg);
            }
        }

        protected void ibtSearch_Click(object sender, ImageClickEventArgs e)
        {
            grvView.DataSource = StudentBL.SearchByName(txtSearch.Text);
            DataBind();
        }

        protected void lbtBackDetail_Click(object sender, EventArgs e)
        {
            pnlDetail.Visible = false;
            pnlView.Visible = true;
        }
    }
}